$(document).ready(function(){
        /* WORKFLOW */
        /* load elements in workflow */
        getWorkflowAction($("#form_id").val()) //for workfklow action
        //handles ctrl-s 
	$(document).keydown(function(event) {
		var currKey=0,e=e||event; 
		currKey=e.keyCode||e.which||e.charCode;  //do this handle FF and IE
		if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;
			event.preventDefault();
			openSaveDialog();
			return false;
	});
        setWorkflow()
})
//open for saving
function openSaveDialog(){
	$( "#divSave" ).dialog({
		height:250,
		width:450,
		modal:true,
		resizable:false
	});
}
//Get Processor depending on the processor type 
function getProcessor(value,selected,reset){
        $.ajax({
        url: url + "loadWfElem/" + value + "/" + selected,
        cache: false
        }).done(function( data ) {
                $(".processor").html( data );
        });
        var initID = $("#node_id").val().split("_")[1];
        //Change some values of node-data(json) on the node
        var node_data =  jQuery.parseJSON($("#node_"+initID).attr("node_data"));
        node_data.processor_type = value;
        //Reset the label of the node
        if(reset==1){
                node_data.processor = 0;
                $("#nodeLabel_"+initID).text("NODE "+initID);
        }
        var node_dataString = JSON.stringify(node_data);
        $("#node_"+initID).attr("node_data",node_dataString)
}

function getWorkflowAction(form_id){
        //for action status
        getActionStatus()
        //for action button
        getActionButton(form_id);
}

function getActionStatus(){
        $.ajax({
        url: url + "loadActionStatus/",
        cache: false
        }).done(function( data ) {
                $(".actionStatus").html( data );
                //alert(url + "loadActionStatus")
        });
}
//get the buttons for workflow
function getActionButton(form_id){
        $.ajax({
        url: url + "loadActionButton/" + form_id,
        cache: false
        }).done(function( data ) {
                $(".setButton").html( data );
                //alert(url + "loadActionStatus")
        });
}

function setProcessor(){
        var value = $(".processor option:selected").val();
        var id = $(".processor option:selected").attr("id");
        var initID = $("#node_id").val().split("_")[1];
        if(id!=0){
                $("#nodeLabel_"+initID).text(value);
                var node_data =  jQuery.parseJSON($("#node_"+initID).attr("node_data"));
                node_data.processor = id;
                var node_dataString = JSON.stringify(node_data);
                $("#node_"+initID).attr("node_data",node_dataString)
        }
}

//get processor and processor type
function getProcessorType(initID){
        //Processor type
        var node_data =  jQuery.parseJSON($("#node_"+initID).attr("node_data"));
        $(".processorType").val(node_data.processor_type);
        //Processor
        getProcessor(node_data.processor_type,node_data.processor)
}
//node(approver) buttons
function setNodeButtons(){
	var value = $(".setButton option:selected").val();
	var id = $(".setButton option:selected").attr("id");
	var rel = $(".setButton option:selected").attr("rel");
	if(rel!="null"){
		$(".nodeButtons").append('<table id="buttonParent_'+rel+'">'+
					 '<tr>'+
						'<td>'+
							'<span style="float:left;margin-top:5px;margin-right:5px;font-size:12px;font-weight:bold">'+value+
						'</td>'+
						'<td>'+
							'<span style="float:right;margin-top:5px;margin-right:5px;cursor:pointer;font-weight:bolder;font-size:10px;color:rgb(226, 173, 173)" id="closeButton_'+rel+'" onclick="deleteButton(this)"> X'+
						'</td>'+
					'</tr>'+
					'<tr>'+
						'<td style="width:100%"> Set Processor:'+
						'</td>'+
						'<td>'+
							'<select class="setProcessor">'+
								'<option value = 0> --Select--</option>'+
								'<option value = 1> Back to Requestor</option>'+
								'<option value = 2> Next Processor</option>'+
								'<option value = 3> Approved</option>'+
							'</select>'+
						'</td>'+
					'</tr>'+
					'<tr>'+
						'<td style="width:100%"> Request Status:'+
						'</td>'+
						'<td>'+
							'<select class="setRequestStatus">'+
								'<option value = 0> --Select--</option>'+
								'<option value = 1> Pending</option>'+
								'<option value = 2> Approve</option>'+
								'<option value = 3> Reject</option>'+
								'<option value = 4> Draft</option>'+
							'</select>'+
						'</td>'+
					'</tr>'+
					'</table>');
		$("#"+id).css("display","none")	
	}
	$(".setButton").val(0)
}
//delete the parent of selected buttons
function deleteButton(obj){
	initID = obj.id.split("_")[1];
	$("#buttonParent_"+initID).remove();
	$("#button_"+initID).css("display","block")
}

function saveNewWorkflow(){
        form_id = $("#form_id").val()
        var ctrNode=0;var ctrLine = 0;//counter
	var nodes = [];var lines = [];//objects in canvas
	$(".outerNode").each(function(){
		ctrNode++;
	})
	$(".lines").each(function(){
		ctrLine++;
	})
	//validation
	if(ctrNode == 0 && ctrLine == 0){
		//empty
		alert("Empty Canvas..");
                //close the modal
                $("#divSave").dialog("close");
	}else{
		if(ctrNode==0){
			//no node
			alert("Empty Node..")
                        //close the modal
                        $("#divSave").dialog("close");
		}else if(ctrLine==0){
			//no line
			alert("Empty Line..")
                        //close the modal
                        $("#divSave").dialog("close");
		}else{
                        //other details
                        workFlowTitle = $("#workFlowTitle").val();
                        workFlowDesc = $("#workFlowDesc").val(); // description
                        delegateRequest = $("#delegateRequest").val()
                        if(workFlowTitle == "" || workFlowDesc ==""){
                                alert("Please complete other information")
                        }else{
                                var nodes = "";var lines = "";
                                //for nodes
                                $(".outerNode").each(function(){
                                        node_data = jQuery.parseJSON($(this).attr("node_data"))
                                        nodes += $(this).attr("id")+"++"+$(this).css("top")+"++"+$(this).css("left")+"++"+node_data.processor_type+"++"+node_data.processor+"++"+node_data.buttons+"{}";
                                })
                                //for lines
                                $(".lines").each(function(){
                                        lines += $(this).attr("class")+"++"+$(this).attr("parent")+"++"+$(this).attr("child")+"++"+$(this).css("top")+"++"+$(this).css("left")+"++"+$(this).css("height")+"++"+$(this).css("width")+"{}";
                                })
                                
                                //ajax request
                                $.ajax({
                                url: url + "saveWorkflow/" + nodes + "/" + lines + "/" + form_id + "/" + workFlowTitle + "/" + workFlowDesc + "/" + delegateRequest,
                                type: "POST",
                                cache: false
                                }).done(function( data ) {
                                        alert(data)
                                        
                                })
                                //remove warning on reloading the page
                                fire_onBeforeOnload(0)
                        }
                }
        }
}
function setWorkflow(){
        setNodesFromDB()
        setLinesFromDB()
        //interaction of nodes
        $(".nodeContent").remove();
}
function setNodesFromDB(){
        var nodes = $(".nodesDB").text();
        var output = "";
        if(nodes!=""){
                nodes2 = nodes.split("{}");
                for(a=0;a<nodes2.length;a++){
                        if(nodes2[a]!=""){
                                unique_id = nodes2[a].split("++")[0].split("_")[1];
                                output+=setNode(unique_id,1,nodes2[a].split("++")[3]+" => "+nodes2[a].split("++")[4],nodes2[a].split("++")[1],nodes2[a].split("++")[2],"55px","125px","");
                        }
                }
        }
        $("#droppable").append(output);
        nodeInteraction()
}
function setLinesFromDB(){
        var lines = $(".linesDB").text();
        var output = "";
        if(lines!=""){
                lines2 = lines.split("{}");
                for(a=0;a<lines2.length;a++){
                        if(lines2[a]!=""){
                                rel = lines2[a].split("++")[0].split(" ")[3];
                                output+=setLineIndiv(lines2[a].split("++")[0],
                                                     lines2[a].split("++")[1],
                                                     lines2[a].split("++")[2],
                                                     removePixelsExt(lines2[a].split("++")[3]),
                                                     removePixelsExt(lines2[a].split("++")[4]),
                                                     removePixelsExt(lines2[a].split("++")[5]),
                                                     removePixelsExt(lines2[a].split("++")[6]),
                                                     rel)
                        }
                }
        }
        $("#droppable").append(output);
}

function removePixelsExt(text){
        return text.substr(0,text.length-2);
}